﻿using System;
using System.Diagnostics;

namespace BlamanticUI.Components;

public class ToastStateStyle
{

    internal ToastStateStyle(ToastSetting setting)
    {
        Setting = setting;
        ToastState = ToastState.Init;

        AnimationId = $"toaster{Guid.NewGuid().ToString().Replace("-", "")}";
    }

    public ToastSetting Setting { get; }
    public ToastState ToastState { get; set; }

    public DateTime TransitionStartTime { get; set; }

    public string AnimationId { get; }

    public int Opacity => 1;

    public string AnimationStyle
    {
        get
        {
            const string template = "animation:{0} {1}ms;";
            switch (ToastState)
            {
                case ToastState.Showing:
                    var showingDuration = RemainingTransitionMilliseconds(Setting.ShowDuration);
                    return string.Format(template, AnimationId,showingDuration);
                case ToastState.Hiding:
                    var hidingDuration = RemainingTransitionMilliseconds(Setting.HideDuration);
                    return string.Format(template, AnimationId, hidingDuration);
                default:
                    return $"opacity: 1;";
            }
        }
    }

    public string TransitionCssClass
    {
        get
        {
            var template = "@keyframes "+AnimationId+" {{from{{ {0}: {1}; }} to{{ {0}: {2}; }}}}";

            switch (ToastState)
            {
                case ToastState.Showing:
                    return string.Format(template, "opacity", 0, Opacity);
                case ToastState.Hiding:
                    return string.Format(template, "opacity", Opacity, 0);
                case ToastState.Visible:
                    return string.Format(template, "width", "100%", "0%");
                default:
                    return string.Empty;
            }
        }
    }

    private int RemainingTransitionMilliseconds(int? transitionDuration)
    {
        var duration = (transitionDuration ?? 0) - (TransitionStartTime - DateTime.Now).Milliseconds;
        this.DebugLine(nameof(RemainingTransitionMilliseconds), $"剩余时间：{duration}ms");
        return duration >= 0 ? duration : 0;
    }
}

public enum ToastState
{
    Init,
    Showing,
    Hiding,
    Visible,
    MouseOver
}

internal static class ToastStateExtensions
{
    public static bool IsShowing(this ToastState state) => state == ToastState.Showing;
    public static bool IsVisible(this ToastState state) => state == ToastState.Visible;
    public static bool IsHiding(this ToastState state) => state == ToastState.Hiding;
}
